package cn.kgc.vue.shiro;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

import java.util.LinkedHashMap;
import javax.servlet.Filter;

@Configuration
public class SpringbootShiroWebConfig {

    /**
     * 将 Shiro 的过滤器添加到 Spring 容器中
     * @param defaultWebSecurityManager 默认的 Web 安全管理器
     * @return ShiroFilterFactoryBean 实例
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);


        //添加自定义的filter 到shiroFilter
        HashMap<String, Filter> filterHashMap = new HashMap<>();
        filterHashMap.put("customer",new WebTokenFilter());
        shiroFilterFactoryBean.setFilters(filterHashMap);


        // 定义拦截规则
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("/user/captcha", "anon"); // 不需要认证
        linkedHashMap.put("/user/unAuth", "anon"); // 不需要认证
        linkedHashMap.put("/user/login", "anon"); // 不需要认证

        // 放行swagger相关静态资源
        linkedHashMap.put("/doc.html","anon");
        linkedHashMap.put("/swagger-resources", "anon");
        linkedHashMap.put("/favicon.ico", "anon");
        linkedHashMap.put("/v2/api-docs", "anon");
        linkedHashMap.put("/webjars/css/app.b2512131.css", "anon");
        linkedHashMap.put("/webjars/js/chunk-vendors.9ff0f717.js", "anon");
        linkedHashMap.put("/webjars/js/app.ed549958.js", "anon");


         linkedHashMap.put("/**", "customer"); // 需要认证

        // 设置未认证用户跳转的 URL
        shiroFilterFactoryBean.setLoginUrl("/user/unAuth");

        // 设置过滤链定义映射
        shiroFilterFactoryBean.setFilterChainDefinitionMap(linkedHashMap);

        return shiroFilterFactoryBean;
    }

    /**
     * 创建 DefaultWebSecurityManager Bean
     * @param realm 自定义的 Realm 实例
     * @return DefaultWebSecurityManager 实例
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm); // 设置自定义 Realm
        return defaultWebSecurityManager;
    }

    /**
     * 创建 CustomerRealm Bean
     * @return CustomerRealm 实例
     */
    @Bean
    public CustomerRealm customerRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }
}
